<template>
    <div id="app" class="page-video" :class="{'page-loading':pageLoading}">
        <scroll-fixed>
            <page-bar>
                <a href="javascript:history.back();" slot="left">
                    <i class="uicon uicon-back-w"></i>
                </a>
                <a href="javascript:;" slot="right" @click="player.muted = !player.muted">
                    <i class="uicon uicon-voice" :class="{'uicon-voice':!player.muted ,'uicon-voice-off':player.muted }"></i>
                </a>
            </page-bar>
        </scroll-fixed>
        <ui-loading v-if="pageLoading">
            <div slot="content"></div>
        </ui-loading>
        <page-error v-else-if="pageError" @refresh="pageRefresh"></page-error>
        <scroll-list v-else class="ui-list" :config="scroll" :disabled="true"  @bottom="loadmore">
            <transition-group name="list" tag="div">
                <div class="video-dec-item" @click.self.stop="playActive($event,item)"  :class="{'active':active == item.id}" v-for="item in info" :key="item.id+'_'+item.page_no" :data-id="'p_'+item.id+'_'+item.page_no" @click="itemClick($event,item)">
                    <div class="player">
                        <div class="player-wrap" v-if="item.play_status < 2" @click.stop.prevent="playItem($event,item)">
                            <i class="uicon uicon-play" v-show="item.play_status == 0"></i>
                            <img :src="item.src" class="bg" v-show="item.play_status == 0">
                            <i class="loading" v-show="item.play_status == 1"></i>
                        </div>
                         <video
                            v-show="item.play_status == 2"
                            @volumechange="volumeChange($event)"
                            @canplay="item.play_status = 2"
                            @error="item.play_status = 2"
                            playsinline="isiPhoneShowPlaysinline" 
                            webkit-playsinline 
                            x-webkit-airplay="" 
                            preload="none" 
                            controls="true"
                            controlsList="nodownload"
                            :poster="item.src"
                            :muted='player.muted'
                            :src="item.video">
                        </video>
                    </div>
                    <div class="cont">
                        <div class="tit">{{item.subtitle}}</div>
                        <div class="info">
                            <p>
                                <span class="sname">
                                    <div class="slogo">
                                        <img :src="item.logo_url" />
                                    </div>
                                    <span>{{item.source.name}}</span>
                                </span>
                                <span>{{item.time}}</span>
                            </p>
                            <p class="tool">
                                <span><i class="uicon uicon-view"></i> {{item.view}}</span>
                                <span><i class="uicon uicon-bar-more-w" @click.stop="popupMore(item)"></i></span>
                            </p>
                        </div>
                    </div>
                </div>
            </transition-group>
            <div class="list-header">
                <p>相关视频</p>
            </div>
            <transition-group name="list" tag="div">
                <div class="video-dec-item" @click.self.stop="playActive($event,item)" :class="{'active':active == item.id}" v-for="item in recom_list" :data-id="'l_'+item.id+'_'+item.page_no" :key="item.id+'_'+item.page_no"  @click="itemClick($event,item)">
                    <div class="player">
                        <div class="player-wrap" v-if="item.play_status < 2" @click.stop.prevent="playItem($event,item)">
                            <i class="uicon uicon-play" v-show="item.play_status == 0"></i>
                            <img :src="item.src" class="bg" v-show="item.play_status == 0">
                            <i class="loading" v-show="item.play_status == 1"></i>
                        </div>
                        <video
                            v-show="item.play_status == 2"
                            @volumechange="volumeChange($event)"
                            @canplay="item.play_status = 2"
                            @error="item.play_status = 2"
                            playsinline="isiPhoneShowPlaysinline" 
                            webkit-playsinline 
                            x-webkit-airplay="" 
                            preload="none" 
                            controls="true"
                            controlsList="nodownload"
                            :poster="item.src"
                            :muted='player.muted'
                            :src="item.video">
                        </video>
                    </div>
                    <div class="cont">
                        <div class="tit">{{item.title}}</div>
                        <div class="info">
                            <p>
                                <span class="sname">
                                    <div class="slogo">
                                        <img :src="item.logo_url" />
                                    </div>
                                    <span>{{item.source.name}}</span>
                                </span>
                                <span>{{item.time}}</span>
                            </p>
                            <p class="tool">
                                <span><i class="uicon uicon-view"></i> {{item.view}}</span>
                                <span><i class="uicon uicon-bar-more-w" @click.stop="popupMore(item)"></i></span>
                            </p>
                        </div>
                    </div>
                </div>
            </transition-group>
         </scroll-list><!-- en dui-list -->
        
        <popup-more :status="moreConfig.status" :config="moreConfig" @report="popupReport" @close="moreConfig.status = false" @unlike="removeItem" @fav="changeFav" @night="changeNight"></popup-more>
        <ui-report v-if="report_status" :id="moreConfig.item.id" :type="moreConfig.item.type" :title="moreConfig.item.title" @cancel="reportCancel" @done="reportDone"/>
    </div>
</template>
<script>
import Items from '../components/items.vue'
import pageBar from '../components/pagebar.vue'
import scrollFixed from '../components/scrollFixed.vue'
import ScrollList from '../components/scrollList.vue'
import MoreBox from '../components/morebox.vue'
import pageError from '../components/pageError.vue'
import offline from '../components/offline.vue'
import UILoading from '../components/loading.vue'

import mxReport from '../mixins/report.js'

//滚动监听器，用于判断是否在滚动
let scrollTime;

function parseItem(item,vue){
    let tmpItem = item;
        tmpItem.play_status = 0;
        tmpItem.url = item.detail_url;
        tmpItem.type = 'video-item';
        tmpItem.src = item.cover_img[0];
        tmpItem.source = {
            name:item.source
        }
        item.page_no = vue.page.page_no;
        tmpItem.view = item.browse_total;
        tmpItem.time = vue.$moment(item.issue_time * 1000).fromNow().replace(' ','');
        return tmpItem
}

export default {
    name:'page-video',
    components:{
        [Items.name]:Items,
        [pageBar.name]:pageBar,
        [scrollFixed.name]:scrollFixed,
        [MoreBox.name]:MoreBox,
        [ScrollList.name]:ScrollList,
        [offline.name]:offline,
        [UILoading.name]:UILoading,
        [pageError.name]:pageError,
    },
    mixins: [mxReport],
    data(){
        return {
            player:{
                muted:false,
                active:'',
                userClick:false,
            },
            page:{
                id:'',
                is_end:false,
                page_no:1
            },
            pageLoading:true,
            pageError:false,
            moreConfig:{
                status:false,
                id:'',
                fav:false,
                night:false,
                item:''
            },
            scroll:{
                pull:false,
                bottom:false,
            },
            active:0,
            info:[],
            recom_list:[]
        }
    },
    mounted(){
        this.$on('pageRefresh',()=>{
            this.page.page_no = 1;
            this.page.is_end = false;
            this.pageLoading = true;
            this.loadPage(true).then(rs=>{
                this.$nextTick(() => {
                    this.scroll.bottom = this.recom_list.length == 0 ? 'hidden' : (this.page.is_end ? 'done' : false);
                });
            }).catch(e=>{
                this.pageError = true;
            }).finally(()=>{
                this.pageLoading = false;
            })
        })

        window.addEventListener('scroll',this.scrollChangeTag,false);

        let parse = this.$utils.urlFactory.parse(location.search);
        if(parse && parse.id){
            this.page.id = parse.id;
            this.$emit('pageRefresh');
        }else{
            this.$toast('参数有误').then(()=>{
                history.back();
            })
        }


        this.$on('PLAYER_PLAY',item=>{
             this.active = item.id;
        })
       
    },
    destroyed(){
        window.removeEventListener('scroll',this.scrollChangeTag,false);
    },
    methods:{
        volumeChange(e){
            this.player.muted = e.currentTarget.muted
        },
        playActive(e,item){
            this.active = item.id;
            if(item.play_status == 0){
                e.currentTarget.querySelector('.player-wrap').click();
            }else{
                this.player.userClick = true;
                this.playVideo(e.currentTarget)
                setTimeout(()=>{
                    this.player.userClick = false;
                },800)
            }
        },
        loadPage(needClean = false){
            let urlParams = this.$utils.urlFactory.parse(location.search);
            let params = {
                id:this.page.id,
                page_no:this.page.page_no
            }
            if(urlParams.action && urlParams.action == 'preview'){
                params.action = 'preview'
            }
            return this.$http.get('?ct=news&ac=video_detail',{params}).then(response=>{
                let {data} = response;
                if(data.code == 0){
                    let rs = data.data;
                    this.page.is_end = !rs.is_have_data;
                    if(this.page.page_no == 1){
                        this.active = rs.info.id;
                        rs.info.detail_url = location.href;
                        //添加历史记录
                        this.$utils.history.set(rs.info);
                        if(!this.$utils.unlike.check(rs.info.id)){
                            this.info = [parseItem(rs.info,this)];
                        }
                    }
                
                    let list = [];
                    rs.list.forEach(item=>{
                        if(this.$utils.unlike.check(item.id)) return;
                        let tmpItem = parseItem(item,this);
                        list.push(tmpItem);
                    });
                    if(!needClean){
                        this.recom_list = this.recom_list.concat(list);
                    }else{
                        this.recom_list = list;
                    }
                    
                    this.page.page_no++;
                }else{
                    let msg = data.msg || '请求异常';
                    let co = this.$toast(msg);
                    if(data.code == 5003 || data.code == 5004){
                        co.then(()=>{
                            history.back();
                        })
                    }
                    throw new Error(msg);
                }
            }).catch(e=>{
                this.$toast(e);
                throw e;
            })
        },
        compareTop(arr,h){
            //每次先计算中间那个
            let midx = parseInt(arr.length / 2);
            let middle = arr[midx];
            let rect = document.querySelector('[data-id="l_'+ middle.id +'_'+middle.page_no+'"]').getBoundingClientRect().top;
            if(rect > h/2){ //从middle前面开始比较
                let len = midx + 1;
                let choose;
                for(let i = len-1;i>=0 ;i--){
                    let lrect = document.querySelector('[data-id="l_'+ arr[i].id +'_'+arr[i].page_no+'"]').getBoundingClientRect();
                    if(lrect.top < 0) break;
                    let mid = lrect.top + lrect.height/2;
                    //最接近中线的就是被选中的孩子啦；
                    let ltop =Math.abs(mid - h/2);
                    if(!choose || choose.top > ltop){
                        choose = {
                            item:arr[i],
                            top:ltop,
                        }
                    }
                }
                return choose;
            }else{//从middle后面开始比较
                let choose;
                for(let i = midx,len = arr.length;i<len ;i++){
                    let lrect =  document.querySelector('[data-id="l_'+ arr[i].id +'_'+arr[i].page_no+'"]').getBoundingClientRect();
                    if(lrect.top >= h) break;
                    //最接近中线的就是被选中的孩子啦；
                    let mid = lrect.top + lrect.height/2;
                    let ltop =Math.abs(mid - h/2);
                    if(!choose || choose.top > ltop){
                        choose = {
                            item:arr[i],
                            top:ltop,
                        }
                    }
                }
                
                return choose;
            }
        },
        playItem(e,item){
            this.player.userClick = true;
            this.active = item.id;
            let rect = e.currentTarget.getBoundingClientRect();
            if(rect.top <0 || rect.height + rect.top > window.innerHeight){
                e.currentTarget.scrollIntoView();
            }
            if(item.play_status == 0){
                item.play_status = 1;
            }
            this.playVideo(e.currentTarget.parentNode);
            setTimeout(()=>{
                this.player.userClick = false;
            },800)
        },
        playVideo(el){
            let video = el.querySelector('video');
            if(!video.paused){
                //video.pause();
            }else{
                this.$el.querySelectorAll('video').forEach(item=>{
                    if(video !== item){
                        item.pause();
                        item.currentTime = 0;
                    }
                
                });
                 video.play();
            }
            
           
        },
        scrollChangeTag(e){
            if(scrollTime){
                clearTimeout(scrollTime);
                scrollTime = '';
            }
            if(this.player.userClick) return false;
            scrollTime = setTimeout(()=>{
                let ReacArr = '';
                let winH = window.innerHeight;
                let items = this.recom_list;
                if(items.length>0){
                //如果第一个的top不是负数的话，那就选择第一个
                    let first,el,choose;
                    if(this.info.length !== 0){
                        el = document.querySelector('[data-id="p_'+ this.info[0].id +'_'+this.info[0].page_no+'"]');
                        first  = el.getBoundingClientRect().top;
                    }else{
                        el = document.querySelector('[data-id="l_'+ this.recom_list[0].id +'_'+this.recom_list[0].page_no+'"]');
                        first  = el.getBoundingClientRect().top;
                    }
                

                    if(first >=0){
                        if(this.info.length !== 0){
                            choose = this.info[0];
                        }else{
                            choose = this.recom_list[0];
                        }
                    }else{
                        choose = this.compareTop(items,winH).item
                        el = document.querySelector('[data-id="l_'+ choose.id +'_'+ choose.page_no+'"]');
                    }
                    
                    this.active = choose.id
                    
                   if(choose.play_status == 0){
                        choose.play_status = 1;
                    }
                        
                    this.playVideo(el)
                }
            },300);
        },
        itemClick(e){
            e.currentTarget.querySelector('video').click();
        },
        itemActive(item){
            this.active = item.id;
        },
        pullLoad(){
            console.log('load');
        },
        changeFav(flag){
            this.moreConfig.fav = flag;
            this.moreConfig.item.is_collect = flag ? 1 : 0;
            this.moreConfig.status = false;
        },
        changeNight(flag){
            this.moreConfig.night = flag;
            this.moreConfig.status = false;
        },
        pageRefresh(){
            this.pageError = false;
            this.$emit('RELOADDATA');
        },
        popupMore(item){
            //关闭视频
            this.moreConfig.id = item.id;
            this.moreConfig.item = item;
            this.moreConfig.fav = !!item.is_collect;
            this.moreConfig.night = false;
            this.moreConfig.status = true;
        },
        loadmore(){
            if(this.scroll.bottom || this.page.is_end) return false;
            this.scroll.bottom = true;
            this.loadPage().then(()=>{
                this.$nextTick(() => {
                    this.scroll.bottom = this.page.is_end ? 'done' : false;
                });
            })
        },
        popupReport(){
            this.report_status = true
            this.moreConfig.status=false
            this.$emit('PLYAER_CLOSE')
        },
        removeItem() {
            this.$emit('PLYAER_CLOSE');
            let item = this.moreConfig.item;
            if(this.info.length >0 && item.id == this.info[0].id){
                this.info = [];
            }else{
                let idx = this.recom_list.indexOf(item);
                this.recom_list.splice(idx, 1);
            }

        },
    }
}
</script>
<style lang="less">
.page-video {
    .page-bar {
        background-color:transparent;
        border:none!important;
    }

    background-color:#282423;
    .player {
        position: relative;
        display:flex;
        padding-top:100 * 211/375%;
        overflow:hidden;

        .loading {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            margin: auto;
            width: 80px;
            height: 80px;
            border: 2px solid #fff;
            border-radius: 50%;
            border-bottom-color: transparent;
            animation: loading 1s infinite linear;
        }
        .player-wrap,img,video,i{
            position: absolute;
            top:0;
            left:0;
            right:0;
            bottom:0;
        }
        img {
            width:100%;
            height:100%;
        }
        video {
            width:100%;
            height:100%;
            display: block;
        }
        .player-wrap {
            z-index:3;
            margin:auto;
        }
        i {
            z-index:2;
            margin:auto;
        }
    }

    .cont {
        padding:30px 24px;
        .tit {
            font-size:32px;
            color:#fff;
            line-height: 48px;
        }
    }
    .info {
        margin-top:22px;
        &,&>p {
            display: flex;
            align-items: center;
        }
        justify-content: space-between;
        height:46px;

        p {
            height:100%;
            color:#919191;
            &:first-child {
                flex:1;
            }
            .sname {
                &,.slogo {
                display: flex;
                align-items: center;
                }
                
                .slogo {
                    justify-content: center;
                    margin-right:20px;
                    width:58px;
                    height:58px;
                    padding:10px;
                    border-radius: 50%;
                    overflow: hidden;
                    background-color:#fff;
                    border:1px solid #efefef;
                }
                img {
                    display: block;
                    width:40px;
                    height:auto;
                }
            font-size: 30px;
        }
            span + span {
                margin-left:10px;
            }
            .uicon-bar-more-w {
                margin-left:30px;
            }
        }
    }
    .tool {
        span {
            display:flex;
            justify-content: center;
            align-items: center;
            height:100%;

            .uicon-view {
                margin-right:.5em;
            }
        }
       
    }
    .video-dec-item {
        position:relative;

        &:not(.active) {
            &::after {
                content:'';
                position:absolute;
                z-index:4;
                top:0;
                left:0;
                width:100%;
                height:100%;
                background-color:rgba(0,0,0,.5);
            }
        }
    }

    .list-header {
        padding:50px 0;
        display: flex;
        justify-content: center;
        align-items: center;
        color:#919191;
        font-size:32px;

        p {
            position:relative;

            &::before,
            &::after {
                content:'';
                position:absolute;
                top:50%;
                transform: translateY(-50%);
                width:33px;
                height:2px;
                background-color:#919191;
            }

            &::before {
                left:-40px;
            }

            &::after {
                right:-40px;
            }
        }
    }
}
</style>


